import json
from datetime import timedelta

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils import timezone
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.core.files.storage import default_storage
from django.conf import settings

from life_style import models
from users.models import Usermodel


# Create your views here.
# 检查用户状态
def user_login_check(request):
    user_info = request.session.get('user_info', None)
    if not user_info:
        return None
    email = user_info['email']
    user = Usermodel.objects.filter(email=email).first()
    return user


# 博客列表页

def blog_list(request):
    user_head = ''
    user = user_login_check(request)
    if not user:
        return redirect('login')
    user_head = user.user_head if user.user_head else ''

    btype = request.GET.get('btype')
    LifestyleType = models.LifestyleType.objects.filter(wz_class=btype).first()
    # all_blog = models.Lifestyle.objects.filter(category=LifestyleType).order_by('-create_time')

    # 获取所有标签
    all_tag = models.LifestyleTag.objects.all().order_by('-create_time')[:10]

    # 搜索处理
    search_word = request.GET.get('search_word', "")
    # 结巴 分词  python 库
    # key_list = ["python","报错","typeerror"]
    if search_word:
        #  contains 全表扫描  -- 慢
        # es  -> ‌Elasticsearch --搜索引擎
        all_blog = models.Lifestyle.objects.filter(title__contains=search_word)
    else:
        all_blog = models.Lifestyle.objects.filter(category=LifestyleType).order_by('-create_time')

    # 处理博客分类数量统计
    catogory_count = {}
    for catogory in models.LifestyleType.objects.all():
        catogory_count[catogory.__str__()] = models.Lifestyle.objects.filter(category=catogory).count()

    # 热度排行
    for blog in all_blog:
        view_nums = models.UserBehavior.objects.filter(action=3).count()
        zan_nums = models.UserBehavior.objects.filter(action=1).count()
        col_nums = models.UserBehavior.objects.filter(action=2).count()
        blog.hot = view_nums + zan_nums + col_nums
        blog.save()
    # 限定一个查询的时间范围(三天内)
    all_blog_hot = all_blog.filter(create_time__gt=timezone.now() - timedelta(days=3)).order_by('-hot')[:5]
    if not all_blog_hot.exists():
        all_blog_hot = all_blog.filter(create_time__gt=timezone.now() - timedelta(days=365)).order_by('-hot')[:5]

    # 分页逻辑增强
    page_number = request.GET.get('page', 1)
    paginator = Paginator(all_blog, 4)

    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)

    context = {
        'all_blog': page_obj,
        'ins_active': "active",
        'user_head': user_head,
        'all_blog_hot': all_blog_hot,
        'catogory_count': catogory_count,
        'all_tag': all_tag,
        'btype': btype
    }
    return render(request, 'classic.html', context)


# 博客详情页
def blog_detail(request, blog_id):
    user_head = ''
    user = user_login_check(request)
    if user:
        user_head = user.user_head if user.user_head else ''
    else:
        return redirect('login')
    blog = models.Lifestyle.objects.filter(id=blog_id).first()

    # 用户行为 浏览记录（优化：合并查询和逻辑判断）
    now = timezone.now()
    recent_view = models.UserBehavior.objects.filter(
        user=user, article=blog, action=3
    ).order_by('-create_time').first()

    # 如果没有浏览记录或者上次浏览超过半小时，创建新的浏览行为
    if not recent_view or (now - recent_view.create_time) > timedelta(hours=0.5):
        models.UserBehavior.objects.create(user=user, article=blog, action=3)

    # 标签与统计信息（优化：统一使用 annotate 和 prefetch 提升性能）
    tags = blog.blogs.all()

    # 使用聚合查询减少数据库请求次数
    from django.db.models import Count, Q

    stats = blog.action.aggregate(
        thumbsUp=Count('id', filter=Q(action=1)),  # 点赞数
        collection=Count('id', filter=Q(action=2)),  # 收藏数
        view_nums=Count('id', filter=Q(action=3)),  # 浏览数
        share=Count('id', filter=Q(action=4)),  # 分享数
        comment=Count('id', filter=Q(action=5)),  # 评论数
    )

    # 获取所有的评论数据
    comments = models.UserBehavior.objects.filter(article=blog, action=5).select_related('user').order_by(
        '-create_time')
    # 构建模板上下文数据
    context = {
        'blog': blog,  # 博客文章对象
        'user_head': user_head,  # 用户头像路径
        'tags': tags,  # 博客标签列表
        'thumbsUp': stats['thumbsUp'],  # 点赞数
        'collection': stats['collection'],  # 收藏数
        'view_nums': stats['view_nums'],  # 浏览数
        'share': stats['share'],  # 分享数
        'comment': stats['comment'],  # 评论数
        'comments': comments,  # 将评论列表传入模
        'ins_active': "active"  # 激活菜单项标识
    }

    # 渲染并返回博客详情页面
    return render(request, 'blog-single.html', context)


# 博客发表页
def blog_publish(request):
    user_info = request.session.get('user_info', None)
    if not user_info:
        return redirect('login')
    username = user_info['username']
    email = user_info['email']
    user = Usermodel.objects.filter(email=email, name=username).first()
    cate = models.LifestyleType.objects.all()
    if request.method == "POST":
        # 获取前端传过来的数据
        json_data = request.body.decode("utf-8")
        data = json.loads(json_data)
        # 处理分类
        category = models.LifestyleType.objects.filter(wz_class=data['category']).first()
        # 博客处理
        blog = models.Lifestyle.objects.create(
            user=user,
            title=data['title'],
            desc=data['desc'],
            body=data['body'],
            category=category,
            fm_image=data['fm_image'],
            status=data['status'],
        )
        # 标签处理
        tags = data['tags']
        for tag in tags:
            models.LifestyleTag.objects.create(
                tag_name=tag,
                blog=blog
            )
        return JsonResponse({'error': 200, 'message': '发布成功'})
    return render(request, 'post-editor.html', {'cate': cate})


# 点赞和收藏
def blog_action(request, blog_id):
    action = request.GET.get('action', '1')
    user = user_login_check(request)
    blog = models.Lifestyle.objects.filter(id=blog_id).first()
    if user:
        # 检查是否已经存在该行为
        existing_behavior = models.UserBehavior.objects.filter(
            user=user,
            article=blog,
            action=action
        ).exists()
        if not existing_behavior:
            # 如果不存在，则创建新行为
            models.UserBehavior.objects.create(
                user=user,
                article=blog,
                action=action
            )
        # 如果存在，不做任何操作
        return redirect('detail', blog_id=blog_id)


# 发表评论
def blog_comment(request):
    user = user_login_check(request)
    if request.method == "POST":
        comment = request.POST.get('comment')
        blog_id = request.POST.get('blog_id')
        models.UserBehavior.objects.create(
            user=user,
            article=models.Lifestyle.objects.filter(id=blog_id).first(),
            action=5,
            comment=comment
        )
        return redirect('detail', blog_id=blog_id)


# 图片上传
def image_upload(request):
    if request.method == 'POST' and request.FILES.get('file'):
        file = request.FILES['file']
        path = default_storage.save("coverImage/" + file.name, file)
        url = settings.MEDIA_URL + path
        return JsonResponse({'url': url})
    return JsonResponse({'error': 400, 'message': '图片上传失败'}, status=400)